package com.common.frame.extension

import java.math.BigDecimal
import java.text.DecimalFormat


fun Double?.format2F(): String {
    if (this == null) {
        return "0"
    }
    return this.format("#.##")
}

fun Float?.format2F(): String {
    if (this == null) {
        return "0"
    }
    return this.format("#.##")
}

fun String?.format2F(): String {
    if (this.isNullOrEmpty()) {
        return "0"
    }
    return this.format("#.##")
}


fun BigDecimal?.format2F(): String {
    if (this == null) {
        return "0"
    }
    return this.format("#.##")
}

fun BigDecimal?.format(pattern: String): String {
    if (this == null) {
        return "0"
    }
    val format = DecimalFormat(pattern)
    return format.format(this)
}


fun String?.floor(): String {
    if (this.isNullOrEmpty() || this.isBlank()) {
        return "0"
    }
    return this.split(".")[0]
}


fun String?.format(pattern: String? = "#.##", floor: Boolean? = false): String {
    if (this.isNullOrEmpty() || this.isBlank()) {
        return "0"
    }
    val str = this.replace(" ", "")
        .replace(",", "")
    if (floor == true) {
        return str.floor()
    }

    if (pattern.isNullOrEmpty()) {
        return this
    }
    val format = DecimalFormat(pattern)
    str.toBigDecimalOrNull()?.let {
        try {
            return format.format(it)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    return "0"
}

fun Double?.format(pattern: String): String {
    if (this == null) {
        return "0"
    }
    val format = DecimalFormat(pattern)
    return format.format(this)
}

fun Float?.format(pattern: String): String {
    if (this == null) {
        return "0"
    }
    val format = DecimalFormat(pattern)
    return format.format(this)
}